package cn.ycl.gateway.filter;


import cn.ycl.gateway.config.ConfigProperty;
import cn.ycl.gateway.config.ResponseResult;
import cn.ycl.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yuanchangliang
 * @date 2022-06-20 09:32
 **/
@Component
public class ApplicationFilter implements GlobalFilter, Ordered {


    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ConfigProperty configProperty;

    /**
     * 是否为白名单uri
     *
     * @param path re
     * @return boolean
     */
    private boolean isWhiteUri(String path) {
        List<String> uriWhiteList = configProperty.getUriWhiteList();
        if (path.startsWith("/login/")) {
            return true;
        }
        List<String> collect = uriWhiteList.stream().filter(uri -> uri.equals(path)).collect(Collectors.toList());
        return collect.size() > 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        String token = serverHttpRequest.getHeaders().getFirst("token");
        String path = serverHttpRequest.getPath().value();
        if (!isWhiteUri(path)) {
            if (Objects.isNull(token)) {
                return getVoidMono(serverHttpResponse);
            }
            String o = (String) redisUtil.get(token);
            //通过以下方式才能转化为UserInfoVO,直接转换报错
//            JSONObject entries = JSONUtil.parseObj(o);
//            UserInfoVO userInfoVO = JSONUtil.toBean(entries, UserInfoVO.class);
            if (Objects.isNull(o)) {
                return getVoidMono(serverHttpResponse);
            }
        }
        return chain.filter(exchange);
    }

    private Mono<Void> getVoidMono(ServerHttpResponse serverHttpResponse) {
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        ResponseResult responseResult = ResponseResult.builder()
                .code("ycl-auth-1001")
                .msg("token不存在或已过期")
                .data("error")
                .build();
        DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(responseResult).getBytes());
        return serverHttpResponse.writeWith(Flux.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
